package com.eastfair.pay.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eastfair.annotation.annotation.security.PreAuth;
import com.eastfair.boot.controller.SuperController;
import com.eastfair.boot.request.PageParams;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.exception.BizException;
import com.eastfair.core.utils.ConvertUtil;
import com.eastfair.echo.core.EchoService;
import com.eastfair.pay.dto.PaymentPlanDTO;
import com.eastfair.pay.dto.PaymentPlanPageQuery;
import com.eastfair.pay.dto.PaymentPlanSaveDTO;
import com.eastfair.pay.dto.PaymentPlanUpdateDTO;
import com.eastfair.pay.entity.PaymentPlan;
import com.eastfair.pay.exceptioncode.PayExceptionCode;
import com.eastfair.pay.service.PaymentPlanService;
import com.eastfair.pay.vo.PaymentPlanVO;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * 前端控制器
 * 付款计划
 * 合同在使用
 * </p>
 *
 * @author clm
 * @date 2022-06-08
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/paymentPlan")
@Api(value = "PaymentPlan", tags = "付款计划")
@PreAuth(replace = "pay:paymentPlan:")
public class PaymentPlanController extends SuperController<PaymentPlanService, Long, PaymentPlan, PaymentPlanPageQuery, PaymentPlanSaveDTO, PaymentPlanUpdateDTO> {

    @Autowired
    private EchoService echoService;
    @Resource
    private PaymentPlanService paymentPlanService;

    @Override
    public void handlerResult(IPage<PaymentPlan> page) {
        // 想让返回值实现自动回显，请将此行代码打开
        // echoService.action(page);
    }

    /**
     * Excel导入后的操作
     *
     * @param list
     */
    @Override
    public R<Boolean> handlerImport(List<Map<String, String>> list) {
        List<PaymentPlan> paymentPlanList = list.stream().map((map) -> {
            PaymentPlan paymentPlan = PaymentPlan.builder().build();
            //TODO 请在这里完成转换
            return paymentPlan;
        }).collect(Collectors.toList());

        return R.success(baseService.saveBatch(paymentPlanList));
    }

    /**
     * 处理参数
     *
     * @param params 分页参数
     */
    @Override
    public void handlerQueryParams(PageParams<PaymentPlanPageQuery> params) {
        PaymentPlanPageQuery pageQuery = params.getModel();
        //分页处理
        if (ContextUtil.getProjectId() != null) {
            pageQuery.setProjectId(ContextUtil.getProjectId());
        }
    }

    /**
     * 更新付款计划
     *
     * @param paymentPlanDTOs
     * @return
     */
    @PostMapping("/saveOrupdate")
    public R saveOrupdate(@RequestBody @Validated List<PaymentPlanDTO> paymentPlanDTOs) {
        String failPlan = paymentPlanService.saveOrupdate(paymentPlanDTOs);
        if (StrUtil.isBlank(failPlan)) {
            return R.success();
        } else {
            return R.result(PayExceptionCode.CONTRACT_PAYMENT_PLAN_UPDATE_ERROR.getCode(), null, null, String.format(PayExceptionCode.CONTRACT_PAYMENT_PLAN_UPDATE_ERROR.getMsg(), failPlan));
        }
    }

    @GetMapping("/delete/{planId}")
    public R delete(@PathVariable("planId") Long planId) {
        try {
            paymentPlanService.deleteById(planId);
            return R.success();
        } catch (BizException biz) {
            return R.fail(biz);
        }

    }


    /**
     * 获取合同付款计划
     *
     * @param businessId
     * @return
     */
    @GetMapping("/queryByContractId/{businessId}")
    public R<List<PaymentPlanVO>> queryByContractId(@PathVariable("businessId") Long businessId) {
        try {
            List<PaymentPlan> paymentPlanList = paymentPlanService.queryByBusinessId(businessId);
            List<PaymentPlanVO> paymentPlanVOS = ConvertUtil.convertList(paymentPlanList, PaymentPlanVO.class);
            return R.success(paymentPlanVOS);
        } catch (BizException biz) {
            return R.fail(biz);
        }

    }


    /**
     * 获取合同付款计划
     *
     * @param params
     * @return
     */
    @PostMapping("/queryPage")
    public R<Page<PaymentPlanVO>> queryPage(@RequestBody @Validated PageParams<PaymentPlanPageQuery> params) {

        try {
            Page<PaymentPlanVO> page = paymentPlanService.queryPage(params);
            return R.success(page);
        } catch (BizException biz) {
            return R.fail(biz);
        }
    }

    /**
     * 通过合同编号获取付款计划
     *
     * @param businessNumber
     * @return
     */
    @GetMapping("/queryByBusinessNumber/{businessNumber}")
    public R<List<PaymentPlanVO>> queryByBusinessNumber(@PathVariable("businessNumber") String businessNumber) {
        try {
            List<PaymentPlan> paymentPlanList = paymentPlanService.queryByBusinessNumber(businessNumber);
            List<PaymentPlanVO> paymentPlanVOS = ConvertUtil.convertList(paymentPlanList, PaymentPlanVO.class);
            return R.success(paymentPlanVOS);
        } catch (BizException biz) {
            return R.fail(biz);
        }
    }

    /**
     * 计划付款时间范围查询未付款的付款计划.
     *
     * @param startPlanPayTime the start plan pay time
     * @param endPlanPayTime   the end plan pay time
     * @return the r
     */
    @GetMapping("query/planPayTime")
    public R<List<PaymentPlanVO>> queryByPlanPayTime(@RequestParam("startPlanPayTime") String startPlanPayTime,
                                                     @RequestParam("endPlanPayTime") String endPlanPayTime) {
        log.info("queryByPlanPayTime - 计划付款时间范围查询未付款的付款计划, startPlanPayTime={}, endPlanPayTime={}", startPlanPayTime, endPlanPayTime);
        return R.successDef(paymentPlanService.listByPlanPayTime(startPlanPayTime, endPlanPayTime));
    }
}
